<template>
  <!-- <transition name="todo" appear> -->
    <li>
      <label for="">
        <input
          type="checkbox"
          :checked="todoObj.done"
          @change="handleCheck(todoObj.id)"
        />
        <!-- 
        如下代码也能实现功能，但是不太推荐，因为有点违反原则，因为修改了props,只不过vue没有监测到
        <input type="checkbox" v-model="todoObj.done"/> -->
        <span v-show="!todoObj.isEdit"> {{todoObj.title}}</span>
        <input
          type="text"
          v-show="todoObj.isEdit"
          :value="todoObj.title"
          @blur="handleBlur(todoObj, $event)"
          @keyup.enter="handleBlur(todoObj, $event)"
          ref="inputTitle"
        />
      </label>
      <button
        class="btn btn-danger"
        @click="handleDelete(todoObj.id)"
      >删除</button>
        <button
          v-show="!todoObj.isEdit"
          class="btn btn-edit"
          @click="handleEdit(todoObj)"
        >编辑</button>
    </li>
  <!-- </transition> -->
</template>

<script>
import pubsub from "pubsub-js";
export default {
  name: "TodoItem",
  props: ["todoObj"],
  methods: {
    handleCheck(id) {
      // 通知App组件将对应的todo对象的done值取反
      this.$bus.$emit("checkTodo", id);
    },
    handleDelete(id) {
      if (confirm("确定删除吗？")) {
        // this.$bus.$emit('deleteTodo', id)
        pubsub.publish("deleteTodo", id);
      }
    },
    // 编辑（文字变输入框）
    handleEdit(todo) {
      // 如果todo身上没有isEdit
      // if(todo.hasOwnProperty('isEdit')) { // 报错
      if (Object.prototype.hasOwnProperty.call(todo, "isEdit")) {
        todo.isEdit = true;
      } else {
        this.$set(todo, "isEdit", true);
      }
      // 在这里写，vue会先执行完代码，再编译模板，所以这时候还不能获取到输入框，输入框display:none;获取不到focus
      // this.$refs.inputTitle.focus()
      // nextTick 所指定的回调会在dom节点更新完毕后执行

      this.$nextTick(function() {
        this.$refs.inputTitle.focus();
      });
    },
    // 失去焦点回调（真正执行修正逻辑）
    handleBlur(todo, e) {
      todo.isEdit = false;
      if (!e.target.value.trim()) return alert("输入不能为空！");
      if (todo.title === e.target.value) return;
      this.$bus.$emit("updateTodo", todo.id, e.target.value);
    }
  }
};
</script>
<style lang="less" scpoed>
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
  label {
    float: left;
    cursor: pointer;
  }
  button {
    float: right;
    display: none;
    margin-top: 3px;
  }
}
li input li label {
  vertical-align: middle;
  margin-right: 6px;
}
li:before {
  content: initial;
}
li:last-child {
  border-bottom: none;
}
li:hover {
  background: #fafafa;
  button {
    display: block;
  }
}
.todo-enter-active {
  animation: todo 1s;
}
.todo-leave-active {
  animation: todo 1s;
}
@keyframes todo {
  from {
    transform: translateX(100%)
  }
  to {
    transform: translateX(0)
  }
}
</style>
